﻿namespace Cars.Console.Renderer
{
    using Common;
    using System;
    using System.Collections.Generic;

    public class ConsoleRenderer : IRenderer
    {
        private int width;
        private int height;

        public ConsoleRenderer(int width, int height)
        {
            this.width = width;
            this.height = height;
            Console.CursorVisible = false;
        }

        public void PrintField()
        {
            int vertical = 5;
            int horisontal = 1;

            var borders = new char[] { '╔', '═', '╗', '╚', '╝', '║' };


            Console.Write(borders[0]);
            for (int i = 1; i < width - 1; i++)
            {
                Console.Write(borders[horisontal]);
            }
            Console.Write(borders[2]);

            for (int i = 1; i < height - 1; i++)
            {
                Console.SetCursorPosition(0, i);
                Console.Write(borders[vertical]);
                Console.SetCursorPosition(width - 1, i);
                Console.Write(borders[vertical]);
            }

            Console.SetCursorPosition(0, height - 1);

            Console.Write(borders[3]);
            for (int i = 1; i < width - 1; i++)
            {
                Console.Write(borders[horisontal]);
            }
            //Console.Write(borders[4]);
            string title = "CARS GAME";
            int leftOffset = title.Length % 2 == 0 ? title.Length / 2 : title.Length / 2 + 1;

            int titleStartPos = width / 2 - leftOffset;

            Console.SetCursorPosition(titleStartPos, 0);
            Console.Write(title);

        }

        public void Clear()
        {
            Console.Clear();
        }

        public void Render(IRenderable renderable)
        {
            var coord = renderable.Coordinates;
            Console.SetCursorPosition(coord.X, coord.Y);
            Console.Write(renderable.Symbol);
        }

        public void Render(IEnumerable<IRenderable> collection)
        {
            foreach (var item in collection)
                this.Render(item);
        }
    }
}
